const serialPort = require('serialPort');
const EventEmitter = require('events');

class portManager extends EventEmitter {
    constructor() {
        super();
    }
    async init(portNum, config) {
        this.portNum = portNum;
        this.config = config;
        try {
            let openFlag = await this.connectPort(portNum, config);
            if (openFlag) {
                this.eventManager();
            }
        } catch (error) {
            console.error(error)
        }
    }
    connectPort(portNum, config) {
        return new Promise((resolve, reject) => {
            this.port = new serialPort(portNum, config, false);
            this.port.open((err) => {
                if (err) {
                    reject(this.portNum + '----open failed--->' + err);
                } else {
                    console.log('<----', this.portNum, 'open succeed--->');
                    resolve(1);
                }
            });//手动打开串口
        })
    }
    eventManager() {
        this.port.on('error', (err) => {
            console.error(this.portNum, '----An error occurred--->', err)

        });
        this.port.on('close', (err) => {
            console.error(this.portNum, '----is disconnected--->', err)
        })
        this.port.on('data', (data) => {
            console.log('data coming----->', data);
        })
    }

    sendMsg(data) {
        return new Promise((resolve, reject) => {
            this.port.write(data, (err) => {
                if (err) {
                    console.log(this.portNum, 'send Msg failed--->', err);
                    resolve(false);//发送错误
                } else {
                    console.log(this.portNum, 'already send Msg--->', data.length > 10 ? data.slice(0, 10) : data, data.length > 10 ? '...' : '');
                    resolve(true);//已发送
                }
            })
        })
    }
}


// function main() {
//     let pm = new portManager()
//     pm.init('COM8', {
//         baudRate: 115200, //波特率
//         dataBits: 8, //数据位
//         parity: 'none', //奇偶校验
//         stopBits: 1, //停止位
//         flowControl: false,
//         autoOpen: false//不自动打开
//     });
//     pm.sendMsg('o000000');
// }

// main()

module.exports = portManager;
